'use strict';

/**
 * 服务调用签名校验
 */
const crypto = require('crypto');

// 【绝密】签名key，可以放到数据库加密保存，通过APP_ID查询得到
const KEY_MAP = new Map([['test0001', '21be83530509abc81aa945a02bec37601cf3cc21']]);
// 过期策略
const SIGN_EXPIRATION = 5 * 60 * 1000; // 秒

exports.verifySign = function (data) {
    try {
        // 超时校验
        const now = Date.now();
        if (data.timestamp > (now + SIGN_EXPIRATION) || data.timestamp < (now - SIGN_EXPIRATION)) {
            return false;
        }
        // 签名校验
        if (data.signature !== sign(KEY_MAP.get(data.appID), data.content)) {
            return false;
        }

        return true;
    } catch (err) {
        return false;
    }
};

exports.getSign = function (req) {
    if (req.query && req.query.signature && req.query.appID && req.query.timestamp) {
        return {
            appID: req.query.appID, signature: req.query.signature, timestamp: req.query.timestamp,
            content: req.query.appID + req.query.timestamp
        };
    }
    return null;
};

/**
 * 签名
 * @param key
 * @param content
 */
function sign(key, content) {
    return crypto.createHash('md5').update(key + content).digest('hex');
}
